package com.bfsuol.yihang.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bfsuol.DocumentTypeConstants;
import com.bfsuol.bfsuolframework.core.controller.SpringControllerSupport;
import com.bfsuol.bfsuolframework.core.controller.json.MessageJson;
import com.bfsuol.bfsuolframework.core.controller.support.Pagination;
import com.bfsuol.bfsuolframework.core.controller.support.QueryParam;
import com.bfsuol.bfsuolframework.core.spring.QueryParameter;
import com.bfsuol.bfsuolframework.core.utils.StringUtils;
import com.bfsuol.bfsuolframework.security.annotations.*;
import com.bfsuol.bfsuolframework.security.dao.Privilege;
import com.bfsuol.bfsuolframework.security.dao.RolePrivilege;
import com.bfsuol.bfsuolframework.security.service._PrivilegeService;
import com.bfsuol.yihang.cars.api.QueryVehicleService;
import com.bfsuol.yihang.cars.dto.VehicleDTO;
import com.bfsuol.yihang.documentFiles.api.QueryDocumentFilesService;
import com.bfsuol.yihang.documentFiles.dto.DocumentFilesDTO;
import com.bfsuol.yihang.documents.api.CommandDocumentService;
import com.bfsuol.yihang.documents.api.QueryDocumentService;
import com.bfsuol.yihang.documents.dto.DocumentDTO;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.swing.text.html.Option;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/yihang/documents")
public class DocumentsController extends SpringControllerSupport {

    @Autowired
    private CommandDocumentService commandDocumentService;
    @Autowired
    private QueryDocumentService queryDocumentService;
    @Autowired
    private QueryVehicleService queryVehicleService;
    @Autowired
    private QueryDocumentFilesService queryDocumentFilesService;

    @SecPrivilege(title = "文档管理")
    @RequestMapping("/index")
    public ModelAndView index(@RequestParam(value = "id",required = false) Long id, Model model){
        if (id!=null){
            VehicleDTO vehicleDTO = queryVehicleService.getById(id);
            model.addAttribute("vehicle",vehicleDTO);
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(getViewNamedPath("index"));
        return modelAndView;
    }

    @SecList
    @RequestMapping("/list")
    public ModelAndView list(
            DocumentDTO documentDTO,
            @ModelAttribute("page") Pagination page){

        com.baomidou.mybatisplus.extension.plugins.pagination.Page page1 = new Page(page.getDefaultCurrentPage(),page.getPageSize());
        com.baomidou.mybatisplus.extension.plugins.pagination.Page documentDTOPage = queryDocumentService.page(page1,documentDTO);
        page.setItems(documentDTOPage.getRecords());
        page.setTotalRecord((int) documentDTOPage.getTotal());

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(getViewNamedPath("list"));
        return modelAndView;
    }

    @RequestMapping("/input")
    public ModelAndView create(@ModelAttribute DocumentDTO documentDTO, Model model){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(getViewNamedPath("input"));
        return modelAndView;
    }

    @RequestMapping("/input/{id}")
    public ModelAndView edit(@PathVariable("id") Long id, Model model){
        DocumentDTO documentDTO = queryDocumentService.getById(id);
        model.addAttribute("document",documentDTO);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(getViewNamedPath("input"));
        return modelAndView;
    }

    @SecCreate
    @SecEdit
    @RequestMapping("/save")
    public @ResponseBody
    MessageJson save(@ModelAttribute DocumentDTO documentDTO){
        try{
            if(documentDTO.getVehicleNo()==null) return MessageJson.fail("车牌号不能为空");
            if(StringUtils.isBlank(documentDTO.getName())) return MessageJson.fail("档案名称不能为空");
            DocumentDTO documentDTO1 = queryDocumentService.getOneByVehicleNo(documentDTO.getVehicleNo());
            if(documentDTO1!=null && documentDTO1.getId()!=null)  return MessageJson.fail("该车辆已存在档案");
            if(documentDTO.isNew()){
                VehicleDTO vehicleDTO = queryVehicleService.getOneByVehicleNo(documentDTO.getVehicleNo());
                if(vehicleDTO == null) return MessageJson.fail("未找到该车辆");
                documentDTO.setVehicleId(vehicleDTO.getId());
                documentDTO.setCreateTime(new Date());
                documentDTO.setUpdateTime(new Date());
                documentDTO.setCreateUserName(this.getLoginInfo().getLoginName());
                documentDTO.setUpdateUserName(this.getLoginInfo().getLoginName());
                commandDocumentService.saveOrUpdate(documentDTO);
            }else{
                documentDTO.setUpdateTime(new Date());
                documentDTO.setUpdateUserName(this.getLoginInfo().getLoginName());
                commandDocumentService.saveOrUpdate(documentDTO);
            }
        }catch (Exception ex){
            return MessageJson.fail(ex.getMessage());
        }
        return MessageJson.information("保存成功");
    }

    @SecDelete
    @RequestMapping("/delete/{id}")
    public @ResponseBody
    MessageJson delete(@PathVariable("id") Long id) {
        if(id != null){
            commandDocumentService.deleteById(id);
        }
        return MessageJson.information("删除成功");
    }

    @RequestMapping("/uploadView/{id}")
    public ModelAndView uploadView(@PathVariable("id") Long id, Model model){
        DocumentDTO documentDTO = queryDocumentService.getById(id);
        model.addAttribute("document",documentDTO);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(getViewNamedPath("upload"));
        return modelAndView;
    }

    @SecCreate
    @SecEdit
    @RequestMapping("/upload")
    public @ResponseBody MessageJson upload(@ModelAttribute DocumentDTO documentDTO){
        try{
            documentDTO.setCreateUserName(this.getLoginInfo().getLoginName());
            documentDTO.setUpdateTime(new Date());
            documentDTO.setUpdateUserName(this.getLoginInfo().getLoginName());
            commandDocumentService.uploadFiles(documentDTO);
        }catch (Exception ex){
            return MessageJson.fail(ex.getMessage());
        }
        return MessageJson.information("保存成功");
    }

    @RequestMapping("/detail/{id}")
    public ModelAndView detailView(@PathVariable("id") Long id, Model model){
        DocumentDTO documentDTO = queryDocumentService.getById(id);
        model.addAttribute("document",documentDTO);
        List<DocumentFilesDTO> documentFilesDTOList = queryDocumentFilesService.findListByDocumentId(id);

        List<DocumentFilesDTO> driverBook = Lists.newArrayList();
        List<DocumentFilesDTO> regixCertificate = Lists.newArrayList();
        List<DocumentFilesDTO> insurePicture = Lists.newArrayList();
        List<DocumentFilesDTO> repaymentPlan = Lists.newArrayList();
        Optional.ofNullable(documentFilesDTOList).orElse(Lists.newArrayList()).stream().forEach(item->{
            if(!StringUtils.isBlank(item.getDocumentType())){
                switch (item.getDocumentType()){
                    case DocumentTypeConstants.GLOBAL_DOCUMENT_TYPE_DRIVING_BOOK:
                        item.setUrl(Base64.getEncoder().encodeToString(item.getFile()));
                        if(item.getFileName().contains("jpg")||item.getFileName().contains("jpeg")||item.getFileName().contains("png")){
                            driverBook.add(item);
                        }
                        break;
                    case DocumentTypeConstants.GLOBAL_DOCUMENT_TYPE_REGIX_CERTIFICATE:
                        item.setUrl(Base64.getEncoder().encodeToString(item.getFile()));
                        if(item.getFileName().contains("jpg")||item.getFileName().contains("jpeg")||item.getFileName().contains("png")){
                            regixCertificate.add(item);
                        }
                        break;
                    case DocumentTypeConstants.GLOBAL_DOCUMENT_TYPE_INSURE_PICTURE:
                        item.setUrl(Base64.getEncoder().encodeToString(item.getFile()));
                        if(item.getFileName().contains("jpg")||item.getFileName().contains("jpeg")||item.getFileName().contains("png")){
                            insurePicture.add(item);
                        }
                       break;
                    case DocumentTypeConstants.GLOBAL_DOCUMENT_TYPE_REPAYMENT_PLAN:
                        item.setUrl(Base64.getEncoder().encodeToString(item.getFile()));
                        if(item.getFileName().contains("jpg")||item.getFileName().contains("jpeg")||item.getFileName().contains("png")){
                            repaymentPlan.add(item);
                        }
                   }
            }
        });
        model.addAttribute("driverBook",driverBook);
        model.addAttribute("regixCertificate",regixCertificate);
        model.addAttribute("insurePicture",insurePicture);
        model.addAttribute("repaymentPlan",repaymentPlan);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(getViewNamedPath("detail"));
        return modelAndView;
    }

}
